<template>
    <template v-for="item in props.menus" :key="item.path">
        <template v-if="!item.meta.hideInMenu">
            <el-sub-menu :index="item.path" v-if="hasChildren(item)">
                <template #title>
                    <el-icon v-if="item.meta.icon"><component :is="item.meta.icon" /></el-icon>
                    <el-icon v-if="!item.meta.icon && settings.collapsed">{{ item.meta.title.slice(0, 1) }}</el-icon>
                    <span>{{ item.meta.title }}</span>
                </template>
                <LayoutMenuItem :menus="item.children" />
            </el-sub-menu>
            <el-menu-item :index="item.path" v-else>
                <el-icon v-if="item.meta.icon"><component :is="item.meta.icon" /></el-icon>
                <el-icon v-if="!item.meta.icon && settings.collapsed && props.firstLevel">
                    {{ item.meta.title.slice(0, 1) }}
                </el-icon>
                <span @click="openLink($event, item.link)">{{ item.meta.title }}</span>
            </el-menu-item>
        </template>
    </template>
</template>

<script lang="ts">
export default {
    name: "LayoutMenuItem",
};
</script>
<script setup lang="ts">
import type { CustomRouteNormallized } from "@/router/type";
import { useSettingsStore } from "@/stores/settings";

type Props = {
    menus: CustomRouteNormallized[];
    firstLevel?: boolean;
};
const props = withDefaults(defineProps<Props>(), { menus: () => [], firstLevel: false });
const settings = useSettingsStore();

const hasChildren = (item: CustomRouteNormallized) => {
    return item.children && item.children.length && item.children.some((child) => !child.meta.hideInMenu);
};

const openLink = (e: any, link: string | undefined) => {
    if (link) {
        e.stopPropagation();
        e.preventDefault();

        window.open(link);
    }
};
</script>

<style lang="scss" scoped>
span {
    flex: 1;
}
</style>
